package me.jiatao.mvpdagger2.mvc.base;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by JiaTao on 2018/8/30.
 * Email: 535318720@qq.com
 * Version: 1.0
 * Description:
 */
public class BasePresenter<V extends IBaseView, M extends IBaseModel> {
    private V mView;
    private M mModel;

    private V mProxyView;

    public BasePresenter(V mView, M mModel) {
        this.mView = mView;
        this.mModel = mModel;

        attach();
    }

    /**
     * 返回代理对象
     *
     * @return
     */
    public V getView() {
        return mProxyView;
    }

    /**
     * 返回当前model
     *
     * @return
     */
    public M getModel() {
        return mModel;
    }

    /**
     * 绑定view
     * 生成view代理类
     * 动态创建model
     */
    private void attach() {
        //使用动态代理处理view为空的情况
        Object objProxyView = Proxy.newProxyInstance(mView.getClass().getClassLoader(), mView.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // 执行这个方法 ，调用的是被代理的对象
                if (mView == null) {
                    return null;
                }
                // 没解绑执行的是原始被代理 View 的方法
                return method.invoke(mView, args);
            }
        });
        mProxyView = (V) objProxyView;
    }

    /**
     * view解绑
     * //
     */
    public void detach() {
        this.mView = null;
    }
}
